package com.dji.GSDemo.GaodeMap.Network;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;


public class HttpVisitor {
    String url;
    Callback callback;

    public static final String  HttpAddressToGetServerIP = "http://121.4.38.14:8080/ip";

    public HttpVisitor(String url,Callback callback){
        this.url = url;
        this.callback = callback;
    }

    public void request() {
        new Thread()
        {
            public void run()
            {
                request(2);
            };
        }.start();
    }

    private void request(int tryTimes){
        try {
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity entity = httpResponse.getEntity();
                String res = EntityUtils.toString(entity, "utf-8");
                callback.onReceive(res);
            } else if(tryTimes>1){
                request(tryTimes -1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public interface Callback {
        void onReceive(String res);
    }
}
